const ousername = document.querySelector(".sjh")
const opassword = document.querySelector(".mm");
const osubmit = document.querySelector(".zc");

osubmit.onclick = function(){
    checkPhone()
    let a = checkPhone();
    if(a){
        // 发起ajax，请求注册功能，携带了用户名和密码
        ajax("http://localhost:3000/api",{
            type:"register",
            username:ousername.value,
            password:opassword.value
        }).then(res=>{
            // 成功
            res = JSON.parse(res);
            // console.log(res);
            if(res.code === 1){
                if(confirm("注册成功，是否哦跳转到登录")){
                    location.href = "./logon.html";
                }
            }else if(res.code === 0){
                // 重名失败
                alert(res.title);
                ousername.value = "";
                ousername.focus();
            }else if(res.code === 2){
                // 数据库错误
                alert(res.title);
            }
        },code=>{
            // 失败
            console.log(code);
        })
    }
}


function ajax(url, data){
    let str = "";
    for(let i in data){
        str += `${i}=${data[i]}&`
    }
    url += "?" + str;

    const xhr = new XMLHttpRequest();
    xhr.open("get", url);
    xhr.send();

    return new Promise((resolve,reject)=>{
        xhr.onload = function(){
            if(xhr.status === 200){
                resolve(xhr.responseText);
            }else{
                reject(xhr.status);
            }
        }
    })
}

function checkPhone(){ 
    
    var phone = document.querySelector('.sjh').value;
    if(!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(phone))){ 
        alert("手机号码有误，请重填");  
        return 0;
    }else{
        return 1;
    }
}